package com.zara.store.web.struts;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.rpc.ServiceException;
import javax.xml.transform.TransformerException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.zara.store.client.clientmodel.Basket;
import com.zara.store.client.clientmodel.BasketProduct;
import com.zara.store.common.IntegrationTransformer;
import com.zara.store.common.PalcHelper;
import com.zara.store.common.PalcVO;
import com.zara.store.common.PalcWsClient;

public class PalcOrderAction extends Action {

	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		HttpSession session = request.getSession();
		PalcOrderForm customForm = (PalcOrderForm) form;
		Log log = LogFactory.getLog(PalcOrderAction.class); 

		Basket basket = (Basket) session.getAttribute("palc");

		if(basket == null) {
			return (mapping.findForward("failure"));			
		}
		
		PalcVO palcVO = basket.createPalc();
		String xmlVO = new PalcHelper().createXmlFromVO(palcVO);
		try {
			String xml = new IntegrationTransformer().transform(xmlVO);
			PalcWsClient palcWsClient = new PalcWsClient();
			if(customForm != null && customForm.getWsdl() != null
					&& customForm.getWsdl().length() > 0) {
				String wsdl = customForm.getWsdl();
				palcWsClient.setWsUrl(wsdl);
			} else {
				palcWsClient.setWsUrl("http://localhost:8080/axis/services/PALC");
			}
			boolean status = palcWsClient.sendPalc(xml);
			log.info("Palc enviado: " + status);
		} catch (TransformerException e) {
			log.info("Palc envio: ex. en transformacion", e);
			e.printStackTrace();
		} catch (ServiceException e) {
			log.info("Palc envio: ex. en servicio", e);
			e.printStackTrace();
		}
		
		session.removeAttribute("palc");
		session.removeAttribute(BasketProduct.class.getName());
		session.setAttribute("palc-print", palcVO);
		
		return (mapping.findForward("palc-print"));
	}

}